﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Xms.Abp.Threading;

namespace Xms.Abp.BackgroundJob;

[Dependency(ServiceLifetime.Transient)]
[BackgroundScheduleName("动态执行计划", nameof(DynamicBackgroundSchedule))]
public class DynamicBackgroundSchedule : BackgroundSchedule
{
    public DynamicBackgroundSchedule(AsyncCronTimer timer, IServiceScopeFactory serviceScopeFactory) : base(timer, serviceScopeFactory)
    {
        CronExpression = "0 0 0 * * ?";
    }

    protected override async Task CreateJobAsync(Guid? tenantId, CancellationToken cancellationToken = default)
    {
        var jobName = BackgroundScheduleInfo.GetProperty<string>("jobName");
        var jonDisplayName = BackgroundScheduleInfo.DisplayName.RemovePostFix("执行计划") + "执行任务";
        Logger.LogDebug("动态执行计划【" + BackgroundScheduleInfo.DisplayName + "】开始创建执行任务：" + jonDisplayName);
        await EnqueueJobAsync(
            jobName,
            jonDisplayName,
            BackgroundScheduleInfo.GetProperty<string>("args"),
            tenantId,
            (BackgroundJobPriority)BackgroundScheduleInfo.GetProperty<long>("priority", 15),
            null,
            BackgroundScheduleInfo.ExtraProperties.ContainsKey("timeout") ? (int)BackgroundScheduleInfo.GetProperty<long>("timeout") : null,
            BackgroundScheduleInfo.ExtraProperties.ContainsKey("timeout") ? (short)BackgroundScheduleInfo.GetProperty<long>("maxTryCount") : null,
            BackgroundScheduleInfo.ExtraProperties.ContainsKey("timeout") ? BackgroundScheduleInfo.GetProperty<string>("retryIntervals").Split(',', StringSplitOptions.RemoveEmptyEntries).Select(r=>int.Parse(r)) : null,
            null,
            BackgroundScheduleInfo.Id,
            cancellationToken);
        Logger.LogDebug("动态执行计划【" + BackgroundScheduleInfo.DisplayName + "】完成创建执行任务：" + jonDisplayName);
    }

    protected override async Task<IEnumerable<Guid?>> GetTenantIdsAsync()
    {
        return await Task.FromResult(new[] { BackgroundScheduleInfo.GetProperty<Guid?>("tenantId", null) });
    }
}
